$NG.AllReady(function (page, { useAction, useValuesChange, useUpdateRow, useDataIndexChange, useUpdateRows, useClick }) {
    var mstform = $NG.getCmpApi('p_form_detailed_design'); //获取表头数据
    var dgrid = $NG.getCmpApi('p_form_detailed_design_d'); //获取表体数据
    const profit = $NG.getCmpApi("p_form_detailed_design_d")
    const headerTable = $NG.getCmpApi("p_form_detailed_design")
    const gridToolbar = $NG.getCmpApi("toolbar_p_form_detailed_design_d")
    gridToolbar.getItem('imp').setProps({children:'引用设备清单明细'})
    if(page.oType == 'add'){

    }
    {//初始化逻辑BEGIN
        if (page.oType == "add" || page.oType == "edit" || page.oType == "copy") {
            fieldSetHidden();
            filterCntMain();
            if (mstform.getItem('phid_pc').getValue()) {
                getProject();
                getCntCount("p_form_detailed_design","u_cnt_name",()=>{
                    getCntInfo()
                })
            };

        }
    }//初始化逻辑END
    {//表头字段变化逻辑BEGIN
        useValuesChange(({ args }) => {
            cleanCntInfo();
            filterCntMain()
            getProject()
            getCntCount("p_form_detailed_design","u_cnt_name",()=>{
                getCntInfo()
            })
        }, 'p_form_detailed_design.phid_pc');
        useValuesChange(({ args }) => {
            getCntInfo();
            // getSbqdInfo()
        }, 'p_form_detailed_design.u_cnt_name');
        //监听深化设计类型
        useValuesChange(({ args }) => {
            fieldSetHidden();
        }, "p_form_detailed_design.u_detailed_type")
        useUpdateRows(({args})=>{
            args[0].forEach((item)=>{
                updateCosts([item])
                caculatedgrid()
            })
            dgrid.refreshView()
        },"p_form_detailed_design_d")
        // 监听是否影响工期
        useValuesChange(({ args }) => {
            console.log(`工期监听`, args);
            const _value = headerTable.getItem("u_is_impact_schedule").getValue()
            console.log(`是否影响工期`, _value);
            let lock = false
            if (Number(_value) == 1) {
                lock = true
            } else {
                lock = false
            }
            $NG.updateUI(function (updater, state) {
                updater.fieldSetForm.p_form_detailed_design.u_is_adjust_schedule.setProps({
                    required: lock, //required是否必输
                });
            });
        }, "p_form_detailed_design.u_is_impact_schedule")

    }//表头字段变化逻辑END

    {//表体订阅字段更新逻辑BEGIN
        // 统一的更新逻辑函数
        function updateCosts(args){
            console.log('updateCosts begin')
            args[0].u_sub_cost_detailed_this = (args[0].u_detailed_qty_this || 0) * (args[0].u_sub_prc || 0);
            args[0].u_sub_cost_detailed = (args[0].u_detailed_qty || 0) * (args[0].u_sub_prc || 0);

            args[0].u_pur_cost_detailed_this = (args[0].u_detailed_qty_this || 0) * (args[0].u_pur_prc || 0);
            args[0].u_pur_cost_detailed = (args[0].u_detailed_qty || 0) * (args[0].u_pur_prc || 0);

            args[0].u_self_cost_detailed_this = (args[0].u_detailed_qty_this || 0) * (args[0].u_self_prc || 0);
            args[0].u_self_cost_detailed = (args[0].u_detailed_qty || 0) * (args[0].u_self_prc || 0);
            dgrid.refreshView()
        };

        // 用于绑定触发字段和更新的通用函数
        const createChangeHandler = (fields) => {
            fields.forEach((field) => {
                useDataIndexChange(({ args, instance }) => {
                    updateCosts(args);
                    instance.updateRow(args[0]);
                    caculatedgrid();
                }, field);
            });
        };
        // 绑定字段变化以触发更新
        createChangeHandler([
            'p_form_detailed_design_d.u_detailed_qty_this',
            'p_form_detailed_design_d.u_detailed_qty',
        ]);


        useDataIndexChange(({ args, instance }) => {

        }, "u_detailed_qty");
        useDataIndexChange(({ args, instance }) => {
            // caculatedgrid();
        }, "u_detailed_qty_this");
    }//表体订阅字段更新逻辑END


    // 方法定义
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    //根据项目筛选合同
    function filterCntMain() {
        console.log(`项目id`, headerTable.getItem("phid_pc").getValue());
        $NG.updateUI((updater, state) => {
            console.log('过滤参数检查', updater);
            updater.fieldSetForm.p_form_detailed_design.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = mstform.getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!mstform.getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 1,//合同类型
                        phid_pc: mstform.getItem("phid_pc").getValue()
                    }
                }),
            });
        });
    }
    // 获取项目信息
    function getProject() {
        if(!mstform.getItem("phid_pc").getValue())return 
        
        
        $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem('phid_pc').getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects
            console.log(`项目信息获取`, datas);
            $NG.updateState((updater) => {
                updater.data.p_form_detailed_design.setProps({
                    u_equipment_list_total_cost: datas.u_total_cost_amt
                    // , u_equipment_list_sub_cost: datas.u_sub_cost_amt
                    // , u_equipment_list_pur_cost: datas.u_pur_cost_amt
                    // , u_equipment_list_self_cost: datas.u_self_cost
                    , u_equipment_list_impl_amt: datas.u_implement_amt
                    , u_equipment_list_svc_amt: datas.u_svc_cost_amt
                    , u_pc_no:datas.pc_no
                    , u_sqgw: {//售前顾问
                        value: datas.user_sqgw_phid,
                        label: datas.user_sqgw_name,
                    },
                    u_project_manager: {//项目经理
                        value: datas.project_manager_phid,
                        label: datas.project_manager_name,
                    },
                    u_customer_manager: {//客户经理
                        value: datas.project_manager_phid,
                        label: datas.project_manager_name,
                    },
                })
            })
        })
    }
    //合同信息获取
    async function getCntInfo() {
        if(!mstform.getItem("u_cnt_name").getValue()) return 
        await getNEWshsj()
        await getSbqdInfo()
        page.oType == 'add'?await getGzdyD2Detail():null

        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_name").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects
            console.log(`合同信息获取`, datas);
            $NG.updateState((updater) => {
                updater.data.p_form_detailed_design.setProps({
                    u_cnt_no: datas.pcm_no//合同编码
                    , u_cnt_revenue: datas.cnt_sum_vat_fc//合同收入
                    , u_customer: {// 客户名称
                        value: datas.customer_id,
                        label: datas.customer_name,
                    },
                })
            })
        })
    }
    //合同信息清空
    function cleanCntInfo(params) {
        $NG.updateState((updater) => {
            updater.data.p_form_detailed_design.setProps({
                u_cnt_no: ''//合同编码
                , u_cnt_name: ''//合同选择
                , u_cnt_revenue: ''//合同收入
                , u_customer: {// 客户名称
                    value: '',
                    label: '',
                },
            })
        })
    }
    // 设置字段是否隐藏
    function fieldSetHidden(params) {
        console.log('深化设计类型监听', mstform.getItem("u_detailed_type").getValue());
        let lock = false
        if (Number(mstform.getItem("u_detailed_type").getValue()) == 1) {
            lock = true
        } else {
            lock = false
        }
        //表体多字段设置属性
        $NG.updateUI((updater) => {
            const fields = ["u_detailed_gp", "u_detailed_gm", "u_revenue_diff", "u_gp_diff"];
            fields.forEach((field) => {
                updater.fieldSetForm.p_form_detailed_design[field].setProps({
                    hidden: lock, //隐藏
                    // required: true, //必输
                    // disabled: true, //只读
                });
            });
        });
    }
    //汇总表体数据到表头
    function caculatedgrid() {
        console.log('caculatedgrid begin')
        let sub_cost_detailed_this = 0;
        let sub_cost_detailed = 0;

        let pur_cost_detailed_this = 0
        let pur_cost_detailed = 0

        let self_cost_detailed_this = 0
        let self_cost_detailed = 0

        let cost_detailed_this = 0
        let cost_detailed = 0
        const Rows1 = $NG.getCmpApi('p_form_detailed_design_d').getRows();
        Rows1.forEach(items => {
            sub_cost_detailed_this += (Number(items.u_sub_cost_detailed_this) || 0)
            sub_cost_detailed += (Number(items.u_sub_cost_detailed) || 0)

            pur_cost_detailed_this +=(Number(items.u_pur_cost_detailed_this) || 0)
            pur_cost_detailed += (Number(items.u_pur_cost_detailed) || 0)

            self_cost_detailed_this += (Number(items.u_self_cost_detailed_this) || 0)
            self_cost_detailed += (Number(items.u_self_cost_detailed) || 0)
        });

        cost_detailed_this = sub_cost_detailed_this + pur_cost_detailed_this + self_cost_detailed_this;
        cost_detailed = sub_cost_detailed + pur_cost_detailed + self_cost_detailed;

        $NG.updateState((updater) => {
            console.log(`sub_cost_detailed_this: ${sub_cost_detailed_this}, sub_cost_detailed: ${sub_cost_detailed}, pur_cost_detailed_this: ${pur_cost_detailed_this}, pur_cost_detailed: ${pur_cost_detailed}, self_cost_detailed_this: ${self_cost_detailed_this}, self_cost_detailed: ${self_cost_detailed}, cost_detailed_this: ${cost_detailed_this}, cost_detailed: ${cost_detailed}`);
            updater.data.p_form_detailed_design.setProps({
                u_detailed_sub_cost: sub_cost_detailed,//
                u_detailed_sub_cost_this: sub_cost_detailed_this,//

                u_detailed_pur_cost_this: pur_cost_detailed_this,//
                u_detailed_pur_cost: pur_cost_detailed,//

                u_detailed_self_cost_this: self_cost_detailed_this,//
                u_detailed_self_cost: self_cost_detailed,//

                u_detailed_total_cost_this: cost_detailed_this,
                // u_detailed_total_cost_this: cost_detailed_this + mstform.getItem('u_equipment_list_impl_amt').getValue() + mstform.getItem('u_equipment_list_svc_amt').getValue(),
                u_detailed_total_cost: cost_detailed
                // u_detailed_total_cost: cost_detailed + mstform.getItem('u_equipment_list_impl_amt').getValue() + mstform.getItem('u_equipment_list_svc_amt').getValue()

            })
        });
        // console.log('u_total_cost_amt_vat:' + mstform.getItem('u_total_cost_amt_vat').getValue());
    }
    async function getSbqdInfo(){
        if(!mstform.getItem("u_cnt_name").getValue())return
        await $NG.execServer("getSbqdDetailByCnt",{cnt:mstform.getItem('u_cnt_name').getValue()},(res)=>{
            if(res.count == 0){
                 return 
            }
            const _data = JSON.parse(res.data)
            console.log(`获取设备清单`,_data);
            let _arr = []
            _data.forEach(items=>{
                const item = items.extendObjects
                _arr.push({...item})
            })
            window._lsz_sbqdDetail = [..._arr]
        })
        
    }
    //获取工作单元中设备清单明细
    async function getGzdyD2Detail(){
        await $NG.execServer("getGzdyD2Detail",{u_cnt:mstform.getItem("u_cnt_name").getValue()},(res)=>{
            console.log(res);
            if(res.count==0)return 
            const _data = JSON.parse(res.data)
            console.log(`获取明细`,_data);
            const _tempData = []
            _data.forEach(items=>{
                const item = items.extendObjects
                // 匹配设备清单明细
                let _map = null
                let count_amt_nfb = 0
                let count_amt_ncg = 0
                let count_amt_nzz = 0
                if(window._lsz_sbqdDetail){
                    window._lsz_sbqdDetail.forEach(sbItem=>{
                        if(sbItem.u_equipment_list_no == item.u_sbqd_no){
                            console.log("匹配成功的设备清单",sbItem);
                            _map={
                                u_equipment_item:sbItem.phid,
                                u_equipment_item_EXName:sbItem.u_equipment_list_name,
                                u_pc_subitem_category:sbItem.u_pc_subitem_category,
                                u_cnt_d_no:sbItem.u_cnt_item_no,
                                u_cnt_d:sbItem.u_cnt_item,
                                u_cnt_item_EXName:sbItem.u_cnt_item_exname,
                                u_cnt_d_EXName:sbItem.u_cnt_item_exname,
                                u_desc:sbItem.u_tech_params,
                                u_unit:sbItem.u_msunit,
                                u_unit_EXName:sbItem.u_msunit_exname,
                                u_equipment_supplier:sbItem.u_brand,
                                u_equipment_supplier_EXName:sbItem.u_brand_exname,
                                u_cnt_qty:sbItem.u_qty,
                                u_cnd_d_prc:sbItem.u_cnt_prc,
                                u_cnt_d_amt:sbItem.u_cnt_amt,
                                u_sub_item:sbItem.u_sub_item,
                                u_sub_item_name:sbItem.u_sub_name,
                                u_sub_item_EXName:sbItem.u_sub_item_exname,
                                u_sub_item_name:sbItem.u_sub_name,
                                u_sub_item_spec:sbItem.u_sub_ggxh,
                                u_sub_item_msunit:sbItem.u_sub_item_msunit,
                                u_sub_item_msunit_EXName:sbItem.u_sub_item_msunit_exname,
                                u_sub_prc:sbItem.u_sub_prc,
                                u_sub_cost:sbItem.u_sub_cost,
                                u_pur_item:sbItem.u_pur_item,
                                u_pur_item_EXName:sbItem.u_pur_item_exname,
                                u_pur_item_name:sbItem.u_pur_name,
                                u_pur_item_spec:sbItem.u_pur_ggxh,
                                u_pur_item_msunit:sbItem.u_pur_item_msunit,
                                u_pur_item_msunit_EXName:sbItem.u_pur_item_msunit_exname,
                                u_pur_prc:sbItem.u_pur_prc,
                                u_pur_cost:sbItem.u_pur_cost,
                                u_pur_cost_detailed:null,//TODO累计深化拟采购成本
                                u_self_item:sbItem.u_self_item,
                                u_self_item_EXName:sbItem.u_self_item_exname,
                                u_self_item_name:sbItem.u_self_name,
                                u_self_item_spec:sbItem.u_self_ggxh,
                                u_self_item_msunit:sbItem.u_self_item_msunit,
                                u_self_item_msunit_EXName:sbItem.u_self_item_msunit_exname,
                                u_self_prc:sbItem.u_self_prc,
                                u_self_cost:sbItem.u_self_cost,
                                u_self_cost_detailed:null,//TODO累计自制深化成本
                            }
                        }
                        count_amt_nfb += (Number(sbItem.u_sub_cost) || 0)
                        count_amt_ncg += (Number(sbItem.u_pur_cost) || 0)
                        count_amt_nzz += (Number(sbItem.u_self_cost) || 0)
                        console.log(count_amt_ncg,count_amt_nfb,count_amt_nzz);
                    })
                    $NG.updateState((updater)=>{
                        updater.data.p_form_detailed_design.setProps({
                            u_equipment_list_sub_cost:count_amt_nfb,
                            u_equipment_list_pur_cost:count_amt_ncg,
                            u_equipment_list_self_cost:count_amt_nzz,
                        })
                    })
                }
                console.log(`测试🔒`,window._lsz_newLock)
                let _isShsjLock = false
                if(window._lsz_newLock&&_map){
                    //计算本次深化数量
                    let _temp = 0
                    console.log(window._lsz_newShsj);
                    
                    window._lsz_newShsj.forEach(elem=>{
                        console.log(item.u_sbqd_no, elem.u_equipment_list_no);
                        if(item.u_sbqd_no == elem.u_equipment_list_no){
                            console.log(item.sum_qty ,elem.current_qty);
                            _temp = (Number(item.sum_qty) || 0)-(Number(elem.current_qty) || 0)
                            _tempData.push({
                                ..._map,
                                u_equipment_list_no:item.u_sbqd_no,//设备清单编码
                                u_detailed_qty_this:_temp,
                                u_detailed_qty:item.sum_qty
                            })
                            _isShsjLock = true
                        }
                    })
                    if(!_isShsjLock){
                        _tempData.push({
                            ..._map,
                            u_equipment_list_no:item.u_sbqd_no,//设备清单编码
                            u_detailed_qty_this:item.sum_qty,
                            u_detailed_qty:item.sum_qty
                        })
                    }
                    
                } else if(_map){
                    _tempData.push({
                        ..._map,
                        u_equipment_list_no:item.u_sbqd_no,//设备清单编码
                        u_detailed_qty_this:item.sum_qty,
                        u_detailed_qty:item.sum_qty
                    })
                }
                
            })
            console.log(`预备数据`,_tempData);
            dgrid.clearRows().then(()=>{
                dgrid.addRows(_tempData)
                sumShReduce()
            })
        })
    }

    function sumShReduce(){
        const _arr = dgrid.getRows()
        _arr.forEach(item=>{
            item.u_sub_cost_detailed_this = (Number(item.u_detailed_qty_this) || 0) * (Number(item.u_sub_prc) || 0)
            item.u_pur_cost_detailed_this = (Number(item.u_pur_prc) || 0) * (Number(item.u_detailed_qty_this) || 0)
            item.u_self_cost_detailed_this = (Number(item.u_self_prc) || 0) * (Number(item.u_detailed_qty_this) || 0)
        })
        dgrid.refreshView()
    }
    // 获取最新的深化设计
    async function getNEWshsj(){
            await $NG.execServer("getNEWshsj",{u_cnt:mstform.getItem("u_cnt_name").getValue()},(res)=>{
            console.log(res);
            if(res.count==0) return 
            window._lsz_newLock = true // 标识已有
            const _data = JSON.parse(res.data)
            console.log(`获取最新`,_data);
            const newData = []
            //提取最新的一条
            const _newRow = _data[0].extendObjects.phid
            _data.forEach(item=>{
                if(item.extendObjects.phid == _newRow){
                    newData.push({...item.extendObjects})
                }
            })
            //缓存最新的深化设计清单
            window._lsz_newShsj = [...newData]
        })
    }
    //获取合同数量
    function getCntCount(table, key, fun) {
        if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
        $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
          console.log(res, "count");
          switch (res.count) {
            case 0:
              return;
            case 1:
              const datas = JSON.parse(res.data)[0].extendObjects;
              const temp_map = {};
              temp_map[key] = datas.phid;
              temp_map[`${key}_EXName`] = datas.bill_name;
              $NG.updateState((updater) => {
                updater.data[table].setProps({
                  ...temp_map,
                });
                setTimeout(() => {
                  if (fun) {
                    fun();
                  }
                }, 200);
              });
          }
        });
      }
});